package cn.javass.dp.flyweight.example3;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class SecurityMgr {

    private static SecurityMgr securityMgr = new SecurityMgr();

    private SecurityMgr() {
    }

    public static SecurityMgr getInstance() {
        //静态不能用this
        return securityMgr;
    }

    /**
     * 运行期间，用来存放人员对应的权限 ，在web应用中 通常放到session中
     */
    private Map<String, Collection<Flyweight>> map = new HashMap<>();

    /**
     * 模拟登陆功能
     * @param user
     */
    public void login (String user) {
        Collection<Flyweight> col = queryByUser(user);
        map.put(user,col);
    }

    public boolean hasPremit(String user, String securityEntity, String premit) {
        Collection<Flyweight> col = map.get(user);
        if (col == null || col.size() == 0) {
            System.out.println("该用户没有任何权限");
            return false;
        }
        for (Flyweight fm : col) {
            System.out.println("fm == " + fm);
            if (fm.match(securityEntity, premit)) {
                return true;
            }
        }
        return false;
    }

    private Collection<Flyweight> queryByUser(String user) {
        Collection<Flyweight> col = new ArrayList<>();
        for (String s : TestDB.colDB) {
            String ss[] = s.split(",");
            if (ss[0].equals(user)) {
                // 用户名作为 外部状态，    安全实体和权限 合体作为 内部状态
                Flyweight am = FlyweightFactory.getInstance().getFlyweight(ss[1] + ',' + ss[2]);
                col.add(am);
            }
        }
        return col;
    }

}
